package com.xiguaji.tiktok.v1.tiktok.help.repository;

import com.xiguaji.tiktok.v1.tiktok.help.dto.HelpCenterArticleSummaryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

//日后有多个分页要求，可以抽象封装工具类
public class HelpArticleExtRepositoryImpl implements HelpArticleExtRepository {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<HelpCenterArticleSummaryDto> findAllArticlesSummaryByMenuId(Long menuId, Integer pageNumber, Integer pageSize) {

        int starter = (pageNumber - 1) * pageSize;
        String sql = "SELECT id,title, url_suffix url,menu_id ,update_time ,create_time ,create_by ,update_by  FROM help_article " +
                " WHERE menu_id = "+menuId+"  AND display = 1 " +
                " ORDER BY update_time DESC limit " + starter + " , " + pageSize;


        List<HelpCenterArticleSummaryDto> list = jdbcTemplate.query(sql, new HelpCenterArticleSummaryDtoRowMapper());
        return list;
    }

    public static class HelpCenterArticleSummaryDtoRowMapper implements RowMapper<HelpCenterArticleSummaryDto> {
        @Override
        public HelpCenterArticleSummaryDto mapRow(ResultSet resultSet, int i) throws SQLException {
            return HelpCenterArticleSummaryDto
                    .builder()
                    .id(resultSet.getLong("id"))
                    .url(resultSet.getString("url"))
                    .menuId(resultSet.getLong("menu_id"))
                    .title(resultSet.getString("title"))
                    .updateTime(resultSet.getLong("update_time"))
                    .createBy(resultSet.getString("create_by"))
                    .updateBy(resultSet.getString("update_by"))
                    .createTime(resultSet.getLong("create_time"))
                    .build();
        }
    }
}
